import tornado.web
import sae.const
import tornado.database
import os.path

from comment import comment
from article import article
from connection import Connection

class CommentHandler(tornado.web.RequestHandler):
    def get(self):
        Comment = []
    	
        db = Connection(sae.const.MYSQL_HOST+":"+sae.const.MYSQL_PORT,sae.const.MYSQL_DB, sae.const.MYSQL_USER, sae.const.MYSQL_PASS, 30)
        for comment_ in db.query("SELECT * FROM comment"):
            TempComment = comment()
            TempComment.set(comment_.id, comment_.content, comment_.time)
            Comment.append(TempComment)

        query = int(self.get_argument("query", "-1"))
        ResComment = [];
        
        db = Connection(sae.const.MYSQL_HOST+":"+sae.const.MYSQL_PORT,sae.const.MYSQL_DB, sae.const.MYSQL_USER, sae.const.MYSQL_PASS, 30)
        Article = db.query("SELECT * FROM article WHERE id = "+str(query))

        for comment_ in Comment:
            if comment_.Id == query:
                ResComment.append(comment_)
        
        ip = self.request.remote_ip
        
        temp = db.query("SELECT * FROM Praise WHERE id='"+str(query)+"' and ip='"+str(ip) + "'")

        self.render("comment.html", query = query, Comments = ResComment, Article = Article, can_zan = not len(temp))

    def post(self):
        query = self.get_argument("query", "")
        content = self.get_argument("comment", "")
        
        if content == "":
        	self.get()
        	return
        
        db = Connection(sae.const.MYSQL_HOST+":"+sae.const.MYSQL_PORT,sae.const.MYSQL_DB, sae.const.MYSQL_USER, sae.const.MYSQL_PASS, 30)
        db.execute("INSERT INTO comment (id, content) VALUES ('" + str(query) + "','"+content + "')")
        old = db.execute("SELECT comments FROM article WHERE id=" + str(query))
        db.execute("UPDATE article SET comments=comments+1 WHERE Id=" + str(query))

        self.redirect("/comments?query="+str(query))
        
        return